package com.wn.confi;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        //创建RedisTemplate对象
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        //设置连接工厂
        template.setConnectionFactory(factory);
        //配置键的序列化器：使用字符串类型
        template.setKeySerializer(new StringRedisSerializer());
        //设置值的序列化器：使用fastjson的序列化器
        template.setValueSerializer(new GenericFastJsonRedisSerializer());
        //设置hash类型的序列化器：分别配置字段和值
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new GenericFastJsonRedisSerializer());
        return template;
    }
    /**
     * 添加Redis缓存配置管理器
     */
    @Bean
    @Primary  //首要的缓存器，因为可能会出现多个缓存器
    public RedisCacheManager redisCacheManager(RedisConnectionFactory factory) {
        //1.创建Redis缓存的配置对象
        RedisCacheConfiguration cacheConfiguration =
                RedisCacheConfiguration.defaultCacheConfig()  //使用默认配置
                        .entryTtl(Duration.ofDays(1))   //默认缓存1天
                        //键使用字符串类型
                        .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                        //值使用JSON字符串
                        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));
        //2.创建Redis缓存管理器
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(cacheConfiguration).build();
        return cacheManager;
    }
}